define(function(require, exports) {
	var pubjs = require('pubjs');
	var $ = require('jquery');
	var util = require('util');
	var view  = require('@base/view');

	// 比例拖拽模块
	var Base = view.container.extend({
		init: function(config) {
			var self = this;

			config = pubjs.conf(config, {
				'class': 'M-commonScale',
				'items': null,
				'width': null,
				'height': null,
				'disabled': false,
				'frontClass': 'front',
				'colorLineOff': 20,
				'ruler': {
					'bottom': 7,
					'left': 0,
					'space': 2
				}
			});

			self.Super('init', arguments);

			self.$dragCache = null;
			self.$isDataDirty = false;
			self.$delayShowId = 0;
			self.$isInited = false;
			self.$disabled = config.get('disabled');
			self.$color = 100;
		},
		afterBuild: function() {
			var self = this;
			var c = self.getConfig();
			var con = self.getDOM();

			self.$bar = $('<div class="M-commonScaleBar" />').appendTo(con);
			self.$ctrs = [];
			self.$tips = [];
			self.$colorLines = [];
			self.$index = 0;
			if (c.items){
				var cnt = c.items.length;
				for (var i=0; i<cnt; i++){
					// 生成拖动块
					self.buildItem(c.items[i]);
				}
				self.measure();
			}
			self.createAsync('ruler', 'modules/ruler.base', c.ruler);
			// Tip被点击时将其置于最前
			self.uiProxy(con, '.M-commonScaleTips', 'click', 'eventTipClick');
		},
		// Tip点击回调
		eventTipClick: function(evt, elm) {
			var el = $(elm);
			var frontClass = this.getConfig('frontClass');
			el.addClass(frontClass).siblings().removeClass(frontClass);
		},
		updateSize: function(){
			var self = this;
			var el = this.getDOM();
			if (self.$isInited){ return true; }
			self.$isInited = true;
			var c = self.getConfig();
			if (!c.width || isNaN(+c.width)){
				self.width = el.width();
			}else {
				self.width = c.width;
			}
			if (c.height > 0){
				el.height(c.height);
			}
			self.$bar.width(self.width);
		},
		/**
		 * 控制块拖动处理函数
		 * @param  {Object} ev 拖动事件对象
		 * @return {Bool}    返回操作是否成功
		 */
		eventCtrs: function(ev){
			var self = this;

			if (self.$disabled) {
				return;
			}

			var d, dx, size, sum;
			switch (ev.type){
				case 'moveDrag':
					d = self.$dragCache;
					if (!d){
						return false;
					}
					dx = Math.min(d[2].size, Math.max(-d[0].size, ev.dx));

					// 更新位置
					d[1].css('left', d[0].next + dx);
					d[3].css('width',d[0].colorLineW+dx);
					d[4].css({
						'width':d[2].colorLineW-dx,
						'left':d[2].colorLineL+dx
					})
					var dx1 = d[0].pos + Math.round(dx / 2);
					var dx2 = d[2].pos + Math.round(dx / 2);
					d[0].tip.css('left', dx1);
					d[2].tip.css('left', dx2);

					// 更新百分比
					sum = d[0].precent + d[2].precent;
					size = d[0].size + d[2].size;
					dx1 = Math.round(sum * (d[0].size + dx) / size);
					dx2 = sum - dx1;
					d[0].num.text(dx1 + '%');
					d[2].num.text(dx2 + '%');
				break;
				case 'startDrag':
					for (var i=0; i<self.$tips.length; i++){
						if (ev.data == self.$tips[i].id){
							self.$dragCache = [self.$tips[i-1], self.$ctrs[i-1], self.$tips[i],self.$colorLines[i-1],self.$colorLines[i]];
							return true;
						}
					}
				break;
				case 'endDrag':
					d = self.$dragCache;
					if (!d){
						return false;
					}
					dx = Math.min(d[2].size, Math.max(-d[0].size, ev.dx));

					d[0].next += dx;
					d[0].pos += Math.round(dx / 2);
					d[2].pos += Math.round(dx / 2);

					size = d[0].size + d[2].size;
					d[0].size += dx;
					d[2].size -= dx;

					sum = d[0].precent + d[2].precent;
					d[0].precent = Math.round(sum * d[0].size / size);
					d[2].precent = sum - d[0].precent;

					sum = d[0].value + d[2].value;
					d[0].value = Math.round(sum * d[0].size / size);
					d[2].value = sum - d[0].value;

					d[0].colorLineW += dx;
					d[2].colorLineW -= dx;
					d[2].colorLineL += dx;
					d[1].css('left', d[0].next);
					d[3].css('width',d[0].colorLineW);
					d[4].css({
						'width':d[2].colorLineW,
						'left':d[2].colorLineL
					})
					d[0].tip.css('left', d[0].pos);
					d[2].tip.css('left', d[1].pos);
					d[0].num.text(d[0].precent + '%');
					d[2].num.text(d[2].precent + '%');
					self.$dragCache = null;
				break;
			}
			return true;
		},

		/**
		 * 计算标签位置
		 * @return {None} 无返回
		 */
		measure: function(force){
			var self = this;
			var el = self.getDOM();
			if (el.width() <= 0){
				if (!self.$delayShowId){
					self.$delayShowId = setInterval(function(){self.measure();}, 300);
				}
				if (!force){
					self.$isDataDirty = true;
					return;
				}
			}else if (self.$delayShowId){
				clearInterval(self.$delayShowId);
				self.$delayShowId = 0;
			}
			self.$isDataDirty = false;
			self.updateSize();

			var i, sum = 0;
			for (i=0; i<self.$tips.length; i++){
				sum += self.$tips[i].value;
			}
			if (sum === 0 && self.$tips.length){
				sum = Math.round(100 / self.$tips.length);
				for (i=1; i<self.$tips.length; i++){
					self.$tips[i].value = sum;
				}
				self.$tips[0].value = 100 - sum * (self.$tips.length - 1);
				sum = 100;
			}

			var w = self.width, cw = 0;
			if (self.$ctrs.length){
				cw = self.$ctrs[0].outerWidth();
				w -= cw * self.$ctrs.length;
			}

			var it, off = 0,latestLeft = 0;
			for (i=0; i<self.$tips.length; i++){
				it = self.$tips[i];
				it.precent = Math.round(it.value / sum * 100);
				it.size = Math.round(w * it.value / sum);
				it.pos = off + Math.round(it.size / 2);
				it.next = off + it.size;
				off = cw + it.next;
				it.num.text(it.precent + '%');
				it.tip.css('left', it.pos);
				it.tip.css('marginLeft', -Math.round(it.tip.outerWidth() / 2));
				if (self.$ctrs.length > i){
					self.$ctrs[i].css('left', it.next);
				}
				self.$colorLines[i].css({
					'width':it.next - latestLeft+4,
					'left': latestLeft
				});
				it.colorLineW = self.$colorLines[i].width();
				it.colorLineL = self.$colorLines[i].position().left;
				latestLeft = off -4;
			}
		},
		/**
		 * 建立标签实例
		 * @param  {Object} item 项目配置对象
		 * @return {Mix}      返回项目标识ID
		 */
		buildItem: function(item){
			var self = this;
			var id = item.id || self.$index++;
			// 确定标签颜色
			var color = util.hsb2rgb(self.$color, 0.70, 0.80);
			self.$color += 130;
			var dom;
			dom = $('<div class="M-commonScaleColorLine"/>').appendTo(self.$bar);
			dom.css('background', color);
			self.$colorLines.push(dom);
			// 生成拖动块
			if (self.$tips.length>0){
				dom = $('<div class="M-commonScaleCtr" data-id="'+id+'"/>').appendTo(self.$bar);
				pubjs.drag(dom, id, self.eventCtrs, self);
				self.$ctrs.push(dom);
			}

			// 生成标签
			dom = $('<div class="M-commonScaleTips"><div></div><span></span><em class="M-commonScaleTipsArrow"></em></div>').appendTo(self.$bar);
			dom.css('background', color);
			dom.find('em').css('border-top-color', color);
			self.$tips.push({
				id: id,
				tip: dom,
				num: dom.children('span'),
				data: item,
				value: (item.value || 0),
				size: 0,
				next: 0,
				pos: 0,
				precent: 0,
				colorLineW:0,
				colorLineL:0
			});

			dom = dom.children('div');
			if (util.isFunc(item.render)){
				dom.html(item.render(item, dom));
			}else if (item.html){
				dom.html(item.html);
			}else {
				dom.text(item.text);
			}

			return id;
		},
		/**
		 * 添加项目
		 * @param {Object} item 标签项目对象
		 * @return {Mix} 返回项目标识ID
		 */
		add: function(item){
			var self = this;
			if (self.$tips.length > 0){
				var v, c = self.$tips.length + 1, sum = 0;
				for (var i=0; i<self.$tips.length; i++){
					if (item.id && item.id == self.$tips[i].id){
						return false;
					}
					if (!item.value){
						v = Math.round(self.$tips[i].value / c);
						self.$tips[i].value -= v;
						sum += v;
					}
				}
				if(!item.value){
					item.value = sum;
				}
			}else if (!item.value){
				item.value = 100;
			}
			var id = self.buildItem(item);
			self.measure();
			return id;
		},
		/**
		 * 删除项目
		 * @param  {Mix} id    要删除的标签标识ID
		 * @return {Bool}    返回操作是否成功
		 */
		remove: function(id){
			var self = this;

			for (var i=0; i<self.$tips.length; i++){
				if (self.$tips[i].id == id){
					break;
				}
			}
			if (i >= self.$tips.length){
				return false;
			}

			// 合并数值, 删除dom对象
			var item = self.$tips.splice(i, 1).pop();
			item.tip.remove();
			var colorLine = self.$colorLines.splice(i,1).pop();
			if(colorLine){
				colorLine.remove();
			}
			if (i > 0){
				i--;
			}
			var dom  = self.$ctrs.splice(i, 1).pop();
			if (dom){
				dom.remove();
			}
			if (i < self.$tips.length){
				var len = self.$tips.length;
				var remain = item.value%len; //求余值
				var average = Math.floor(item.value/len); // 平均值
				// 将删除的流量平均分配到各项中
				for(var j=0; j<len; j++){
					self.$tips[j].value += average;
				}
				// 有余值的时候，最后一项加余值
				self.$tips[len-1].value += remain;
			}
			self.measure();
			return true;
		},
		/**
		 * 重置数据, 删除所有标签
		 * @return {None} 无返回
		 */
		reset: function(){
			var self = this;
			var c = self.getConfig();

			while (self.$ctrs.length){
				self.$ctrs.shift().remove();
			}
			while (self.$tips.length){
				self.$tips.shift().tip.remove();
			}
			while(self.$colorLines.length){
				self.$colorLines.shift().remove();
			}
			c.items = null;
			self.$dragCache = null;
			self.$isDataDirty = false;
			if (self.$delayShowId){
				clearInterval(self.$delayShowId);
				self.$delayShowId = 0;
			}
			// self.isHide = false;
			self.$index = 0;
		},
		/**
		 * 设置数据
		 * @param {Array} data 节点数据数组
		 */
		setData: function(data){
			var c = this.getConfig();
			this.reset();

			if (data){
				c.items = data;
				var cnt = data.length;
				for (var i=0; i<cnt; i++){
					// 生成拖动块
					this.buildItem(data[i]);
				}
				this.measure();
			}
		},
		/**
		 * 获取分配的选项值
		 * @return {Object} 分配值对象, key是选项的标识ID
		 */
		getData: function(){
			if (this.$isDataDirty){
				this.measure(true);
			}
			var data = {};
			for (var i=0; i<this.$tips.length; i++){
				data[this.$tips[i].id] = this.$tips[i].value;
			}
			return data;
		},
		/**
		 * 获取分配的
		 * @return {Object} 分配值对象, key是选项的标识ID
		 */
		getPercent: function(){
			if (this.$isDataDirty){
				this.measure(true);
			}
			var data = {};
			for (var i=0; i<this.$tips.length; i++){
				data[this.$tips[i].id] = this.$tips[i].precent;
			}
			return data;
		}
	});

	exports.base = Base;
});